﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ConcordWinManager
{
    public partial class ContragentForm : Form
    {
        public Contragent contragent;

        private Form parentForm;

        string typeContragent = string.Empty;

        public ContragentForm(Form parentForm)
        {
            InitializeComponent();

            contragent = new Contragent();

            this.parentForm = parentForm;
        }

        public ContragentForm(Form parentForm, string type)
        {
            InitializeComponent();

            contragent = new Contragent();

            this.parentForm = parentForm;

            switch (type)
            {
                case "ФЛ":
                    radioBtnFizLico.Checked = true;
                    break;
                case "ЮЛ":
                    radioBtnUrLico.Checked = true;
                    break;
                case "ИП":
                    radioBtnIndPredp.Checked = true;
                    break;
                default:
                    this.Close();
                    break;

            }
        }

        BindingSource bs = new BindingSource();

        public void UpdateForm()
        {
            if (typeContragent != "")
            {
                DataSet ds = new DataSet();
                
                Tools.RunWithProgressIndicator(this, delegate { contragent.SelectByType(this.typeContragent, ref ds); });
                
                bs.DataSource = null;
                bs.Filter = "";
                bs.DataSource = ds.Tables[0];
                

                dataGridViewTable.DataSource = bs;//ds.Tables[0];
                dataGridViewTable.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

                //id_contragent
                dataGridViewTable.Columns[0].Visible = false; 

                //id_address
                dataGridViewTable.Columns[1].Visible = false;

                //Deleted
                dataGridViewTable.Columns[2].Visible = false;

                //Сортировка по столбцу ID
                dataGridViewTable.Sort(dataGridViewTable.Columns[3], ListSortDirection.Ascending);

                dataGridViewTable.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                dataGridViewTable.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                dataGridViewTable.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                dataGridViewTable.Columns[6].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

                dataGridViewTable.Refresh();               
            }
        }
        
                
        private void btnAdd_Click(object sender, EventArgs e)
        {
            contextMenuStripAddType.Show(btnAdd.PointToScreen(new Point(0, 0)));
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            int id;
            if (dataGridViewTable.SelectedRows.Count > 0)
            {
                if (int.TryParse(dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["id_contragent"].Value.ToString(), out id))
                {
                    switch (this.typeContragent)
                    {
                        case "ФЛ":
                            ContragentFLEditForm contragentFLEditForm = new ContragentFLEditForm(this, "Изменение", id, this.typeContragent);
                            contragentFLEditForm.ShowDialog();
                            break;
                        case "ЮЛ":
                            ContragentULEditForm contragentULEditForm = new ContragentULEditForm(this, "Изменение", id, this.typeContragent);
                            contragentULEditForm.ShowDialog();
                            break;
                        case "ИП":
                            ContragentIPEditForm contragentIPEditForm = new ContragentIPEditForm(this, "Изменение", id, this.typeContragent);
                            contragentIPEditForm.ShowDialog();
                            break;
                        default:
                            //this.Close();
                            break;
                    }

                    UpdateForm();
                }
            }
        }


        private void btnChangeItem_Click(object sender, EventArgs e)
        {

            Tools.RunWithProgressIndicator(this, delegate
            {
                //try
                if (dataGridViewTable.SelectedRows.Count>0)            
                {
                    this.contragent.SelectById(
                        (int)dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["id_contragent"].Value,
                        typeContragent);
                }
               // catch { ;}
            });

            this.Close();

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ContragentForm_Load(object sender, EventArgs e)
        {
            btnDelete.Visible = Settings.consultant.user.CanDeleteContragent;
        }

        private void radioBtnFizLico_CheckedChanged(object sender, EventArgs e)
        {
            this.typeContragent = "ФЛ";
            if (radioBtnFizLico.Checked)
            {
                UpdateForm();
            }
        }

        private void radioBtnUrLico_CheckedChanged(object sender, EventArgs e)
        {
            this.typeContragent = "ЮЛ";
            if (radioBtnUrLico.Checked)
            {
                UpdateForm();
            }
        }

        private void radioBtnIndPredp_CheckedChanged(object sender, EventArgs e)
        {
            this.typeContragent = "ИП";
            if (radioBtnIndPredp.Checked)
            {
                UpdateForm();
            }
        }

        private void toolStripMenuItemFL_Click(object sender, EventArgs e)
        {
            ContragentFLEditForm contragentFLEditForm = new ContragentFLEditForm(this, "Добавление");
            contragentFLEditForm.ShowDialog();

            this.typeContragent = "ФЛ";
            radioBtnFizLico.Checked = true;
                        
            UpdateForm();
            //выделение строки добавленного контрагента
            Tools.SelectRowInDataGridViewById("ID", contragentFLEditForm.contragent.id_contragent, ref bs);
        }

        private void toolStripMenuItemUL_Click(object sender, EventArgs e)
        {
            ContragentULEditForm contragentULEditForm = new ContragentULEditForm(this, "Добавление");
            contragentULEditForm.ShowDialog();

            this.typeContragent = "ЮЛ";
            radioBtnUrLico.Checked = true;

            UpdateForm();
            //выделение строки добавленного контрагента
            Tools.SelectRowInDataGridViewById("ID", contragentULEditForm.contragent.id_contragent, ref bs);
        }

        private void toolStripMenuItemIP_Click(object sender, EventArgs e)
        {
            ContragentIPEditForm contragentIPEditForm = new ContragentIPEditForm(this, "Добавление");
            contragentIPEditForm.ShowDialog();

            this.typeContragent = "ИП";
            radioBtnIndPredp.Checked = true;

            UpdateForm();
            //выделение строки добавленного контрагента
            Tools.SelectRowInDataGridViewById("ID", contragentIPEditForm.contragent.id_contragent, ref bs);
        }

        private void tbxQuickSearch_TextChanged(object sender, EventArgs e)
        {
            Tools.QuickSearch(tbxQuickSearch.Text.Trim(), dataGridViewTable.Columns, ref this.bs);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DeleteForm deleteForm = new DeleteForm();
            deleteForm.ShowDialog();

            bool b = false;

            if (deleteForm.DialogResult == DialogResult.OK)
            {
                
                Tools.RunWithProgressIndicator(this, delegate
                {
                    //try
                    if (dataGridViewTable.SelectedRows.Count > 0)
                    {
                        this.contragent.SelectById(
                            (int)dataGridViewTable.Rows[dataGridViewTable.SelectedCells[0].RowIndex].Cells["id_contragent"].Value,
                            typeContragent);
                    }
                    // catch { ;}

                    b = this.contragent.DeleteById(
                        this.contragent.id_contragent,
                        Settings.consultant.id_consultant,
                        deleteForm.ReasonDelete,
                        deleteForm.ShowInReport);
                });

                if (b)
                {
                    MessageBox.Show("Контрагент удален успешно", "Информация!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Контрагент НЕ удален", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
                }

                UpdateForm();
            }

        }

        /// <summary>
        /// Экспорт контрагентов в MS Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExportContragent_Click(object sender, EventArgs e)
        {            
            MSExcelReportGenerator ms = new MSExcelReportGenerator();

            bool deleted = false;

            Tools.RunWithProgressIndicator(this, delegate
            {
                ms.ExportContragent(deleted);
            });
        }
    }
}
